<template xmlns:v-slot="">
  <div class="usere">
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--下面的线-->
    <el-divider></el-divider>

    <!--搜索框-->
    <el-input @keyup.enter.native="searchUser" placeholder="请输入内容" v-model="inputValue" clearable>
      <el-button @click="searchUser" slot="append" icon="el-icon-search"></el-button>
    </el-input>
    <!--添加用户按钮-->
    <el-button @click="showaddDialog" type="success" plain>添加用户</el-button>

    <!--表格-->
    <br><br>
    <template>
      <el-table :data="userList" border style="width: 100%">

        <el-table-column prop="username" label="名字" width="180">
        </el-table-column>

        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>

        <el-table-column prop="mobile" label="电话">
        </el-table-column>

        <el-table-column label="用户状态">
          <!-- 开关 使用插槽 -->
          <template v-slot:default="obj">
            <!--{{ obj.row }}-->
            <el-switch
              @change="changeState(obj.row.id, obj.row.mg_state)"
              v-model="obj.row.mg_state"
              active-color="#13ce66"
            inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <!-- 使用插槽 -->
          <template v-slot:default="{ row }">
            <el-button @click="showEditDialog(row)"  size="small" plain type="primary" icon="el-icon-edit"></el-button>
            <el-button @click="delUser(row.id)" size="small" plain type="danger" icon="el-icon-delete"></el-button>
            <el-button @click="showAssignDialog(row)" size="small" plain type="success" icon="el-icon-check">分配角色</el-button>
          </template>
        </el-table-column>

      </el-table>
    </template>

    <!--分页-->
    <!--@size-change 每页条数变化时触发-->
    <!--@current-change 当前页变化触发-->
    <br>
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[2, 4, 6, 8]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!--添加用户框-->
    <el-dialog
      @close="closeDialog"
      title="添加用户"
      :visible.sync="dialogVisible"
      width="30%"
      @keyup.enter.native="addUser">

      <el-form :rules="rules" ref="form" :model="form" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机"></el-input>
        </el-form-item>
      </el-form>

      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button @click="addUser" type="primary">确 定</el-button>
        </span>
      </template>

    </el-dialog>

    <!--修改用户框-->
    <el-dialog
      title="修改用户"
      :visible.sync="editVisible"
      width="30%"
      @keyup.enter.native="editUser">

      <el-form :rules="rules" ref="editForm" :model="editForm" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-tag type="info">{{ editForm.username }}</el-tag>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile" placeholder="请输入手机"></el-input>
        </el-form-item>
      </el-form>

      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button @click="editUser" type="primary">确 定</el-button>
        </span>
      </template>

    </el-dialog>

    <!--分配角色框-->
    <el-dialog
      title="分配角色"
      :visible.sync="assignVisible"
      width="30%"
      @keyup.enter.native="assignRole">

      <el-form :model="assignForm" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-tag type="info">{{ assignForm.username }}</el-tag>
        </el-form-item>

        <el-form-item label="角色列表">
          <el-select v-model="assignForm.rid" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="assignVisible = false">取 消</el-button>
          <el-button @click="assignRole" type="primary">确 定</el-button>
        </span>
      </template>

    </el-dialog>
</div>
</template>

<script>

export default {
  data () {
    return {
      // 输入框的值
      inputValue: '',
      // 搜索条件
      query: '',
      // 当前页
      pagenum: 1,
      // 每页条数
      pagesize: 2,
      // 总条数
      total: 0,
      // 后台返回的数据进行接收
      userList: [],
      // 显示隐藏添加用户框
      dialogVisible: false,
      // 添加信息默认值
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 表单校验
      rules: {
        // blur 失去焦点时触发
        // change 值修改时触发
        username: [
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: ['blur', 'change'] }
        ],
        email: [
          { type: 'email', message: '请输入邮箱', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入电话', trigger: ['blur', 'change'] }
        ]
      },
      // 显示隐藏修改用户框
      editVisible: false,
      // 修改用户
      editForm: {
        // 用于修改
        id: '',
        // 用于给用户展示
        username: '',
        email: '',
        mobile: ''
      },
      // 显示隐藏分配角色框
      assignVisible: false,
      // 分配角色
      assignForm: {
        username: '',
        // 用户id
        id: '',
        // 角色id
        rid: ''
      },
      // 分配角色
      options: []
    }
  },
  created () {
    // 进来就进行渲染
    this.getUserList()
  },
  methods: {
    // 分页
    // 每页条数变化时触发
    handleSizeChange (val) {
      // 修改每页多少条时
      this.pagesize = val
      // 每次修改后都显示第一页
      this.pagenum = 1
      // 重新渲染
      this.getUserList()
    },

    // 当前页变化触发
    handleCurrentChange (val) {
      // 修改当前页
      this.pagenum = val
      // 重新渲染
      this.getUserList()
    },

    // 封装渲染函数
    async getUserList () {
      const res = await this.$axios.get('users', {
        // get请求的参数, 将来会被拼接到地址栏中
        params: {
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      })
      const { data, meta } = res
      if (meta.status === 200) {
        this.userList = data.users
        // 保存后台返回的总条数
        this.total = data.total
      } else {
        this.$message.error(meta.msg)
      }
    },

    // 搜索
    searchUser () {
      // 点击时，需要修改搜索条件
      this.query = this.inputValue
      // 重置成第一页开始展示
      this.pagenum = 1
      // 重新渲染
      this.getUserList()
    },

    // 修改状态
    async changeState (id, type) {
      const res = await this.$axios.put(`users/${id}/state/${type}`)
      const { meta } = res
      if (meta.status === 200) {
        this.$message.success(meta.msg)
      } else {
        this.$message.error(meta.msg)
      }
    },

    // 删除用户
    async delUser (id) {
      try {
        await this.$confirm('你确定要删除吗?', '温馨提醒', {
          type: '小个子'
        })
        const res = await this.$axios.delete(`users/${id}`)
        const { meta } = res
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          if (this.userList.length === 1 && this.pagenum > 1) {
            this.pagenum--
          }
          this.getUserList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },

    // 显示添加用户框
    showaddDialog () {
      this.dialogVisible = true
    },

    // 添加用户
    async addUser () {
      try {
        // 表单校验
        await this.$refs.form.validate()
        // 发ajax
        const res = await this.$axios.post('users', this.form)
        const { meta } = res
        if (meta.status === 201) {
          this.$message.success(meta.msg)
          // 隐藏模态框
          this.dialogVisible = false
          // 重新渲染
          this.getUserList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },

    // 关闭添加用户进行输入框的清空
    closeDialog () {
      // console.log('只要对话框被关闭了, 就会触发')
      this.$refs.form.resetFields()
    },

    // 显示修改用户框
    showEditDialog (row) {
      // 显示修改框
      this.editVisible = true
      // 进行原来数据的回显
      this.editForm.id = row.id
      this.editForm.username = row.username
      this.editForm.email = row.email
      this.editForm.mobile = row.mobile
    },

    // 修改用户信息
    async editUser () {
      try {
        // 1.先校验
        await this.$refs.editForm.validate()
        // 2.发送ajax
        const { id, email, mobile } = this.editForm
        const { meta } = await this.$axios.put(`users/${id}`, { email, mobile })
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          // 关闭对话框
          this.editVisible = false
          // 重新渲染
          this.getUserList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },

    // 显示分配用户框
    async showAssignDialog (row) {
      // 显示修改框
      this.assignVisible = true
      this.assignForm.id = row.id
      this.assignForm.username = row.username

      // 获取对应的 rid (角色id)
      const resUser = await this.$axios.get(`users/${row.id}`)
      if (resUser.meta.status === 200) {
        const rid = resUser.data.rid
        this.assignForm.rid = rid === -1 ? '' : rid
      }

      // 发送ajax获取角色列表
      const { data, meta } = await this.$axios.get('roles')
      if (meta.status === 200) {
        this.options = data
      } else {
        this.$message.error(meta.msg)
      }
    },

    // 发送ajaxqi请求，修改角色
    async assignRole () {
      const { id, rid } = this.assignForm
      if (rid === '') {
        this.$message.error('请选择角色')
        return
      }
      const { meta } = await this.$axios.put(`users/${id}/role`, { rid })
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        // 隐藏框
        this.assignVisible = false
        // 重新渲染
        this.getUserList()
      } else {
        this.$message.error(meta.msg)
      }
    }
  }
}
</script>

<style scoped lang="less">

  /*搜索框的宽度*/
  .el-input {
    width: 300px;
    margin-right: 40px;
  }

</style>
